#!/usr/bin/env node

import { MCPAntDServer } from './core/MCPAntDServer.js';
import { DatabaseMCPServer } from './core/DatabaseMCPServer.js';

/**
 * 主入口函数 - 支持数据库和内存两种模式
 */
async function main() {
  // 检查启动模式
  const useDatabase = process.env.USE_DATABASE === 'true' || process.env.NODE_ENV === 'production';
  
  console.error(`🚀 启动模式: ${useDatabase ? '数据库模式' : '内存模式'}`);
  
  let server: MCPAntDServer | DatabaseMCPServer;
  
  if (useDatabase) {
    // 数据库模式
    server = new DatabaseMCPServer();
  } else {
    // 内存模式（兼容原有版本）
    server = new MCPAntDServer();
  }
  
  // 处理进程信号
  process.on('SIGINT', async () => {
    console.error('Received SIGINT, shutting down gracefully...');
    try {
      if ('shutdown' in server) {
        await server.shutdown();
      }
    } catch (error) {
      console.error('Error during shutdown:', error);
    }
    process.exit(0);
  });

  process.on('SIGTERM', async () => {
    console.error('Received SIGTERM, shutting down gracefully...');
    try {
      if ('shutdown' in server) {
        await server.shutdown();
      }
    } catch (error) {
      console.error('Error during shutdown:', error);
    }
    process.exit(0);
  });

  try {
    await server.run();
  } catch (error) {
    console.error('❌ Failed to start MCP Ant Design Server:', error);
    process.exit(1);
  }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(console.error);
}